/**
 * 路径解析
 */
export const pathResolve = (...paths: string[]) => {
  let resolvePath = '';
  let isAbsolutePath = false;
  for (let i = paths.length-1; i > -1; i--) {
    let path = paths[i];
    if (isAbsolutePath) break;
    if(!path) continue 
    resolvePath = path + '/' + resolvePath;
    isAbsolutePath = path.charCodeAt(0) === 47;
  }
  if (/^\/+$/.test(resolvePath)) {
    resolvePath = resolvePath.replace(/(\/+)/,'/')
  } else {
    resolvePath = resolvePath.replace(/(?!^)\w+\/+\.{2}\//g, '')
    .replace(/(?!^)\.\//g,'')
    .replace(/\/+$/, '')
  }
  resolvePath = resolvePath.replace("//", "/")
  return resolvePath;
}

/**
 * 时间格式化
 */
export function dateFormat(time: number | Date, type: string){
  let formatTime: string
  let date: Date
  if(time === 0) {
    date = new Date()
  } else {
    date = new Date(time)
  }
  let Year = date.getFullYear()
  let month = date.getMonth() + 1
  let Month = month >= 10 ? month : '0' + month
  let day = date.getDate()
  let Day = day >= 10 ? day : '0' + day
  let Hour = date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()
  let Minute = date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()
  let Second = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds()
  if(type === 'yyyy-MM-dd'){
    formatTime = Year + '-' + Month + '-' + Day
    return formatTime
  } else if (type === 'yyyy-MM-dd hh:mm:ss'){
    formatTime = Year + '-' + Month + '-' + Day + ' ' + Hour + ':' + Minute + ':' + Second
    return formatTime
  } else if (type === 'hh:mm:ss'){
    formatTime = Hour + ':' + Minute + ':' + Second
    return formatTime
  } else {
    return "error type!"
  }
}


/**
 * 时间格式化
 * @param date 时间对象(例：new date())
 * @param fmt 格式化格式（例：yyyy-MM-dd）
 */
export const dateFormatRegular = (date: Date, fmt: string) => {
  let o = {
    "M+": date.getMonth() + 1, //月份
    "d+": date.getDate(), //日
    "h+": date.getHours(), //小时
    "m+": date.getMinutes(), //分
    "s+": date.getSeconds(), //秒
    "q+": Math.floor((date.getMonth() + 3) / 3), //季度
    S: date.getMilliseconds() //毫秒
  };
  if (/(y+)/.test(fmt))
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (let k in o)
    if (new RegExp("(" + k + ")").test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
      );
  return fmt;
};

/**
 * 下载文件
 */
export const downloadFile = (url: string) => {
  const aTag = document.createElement('a')
  let time = new Date().valueOf()
  aTag.href = url + `?time=${time}`
  aTag.target = '_blank'
  aTag.click()
}

/**
 * 判断是否是图片文件
 */
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico', '.tiff', '.raw', '.heif', '.heic']
export const isImage = (filename: string): boolean => {
  const filenameRegex = /[^/\\&\?]+\.\w{2,}$/;
  const matchedFilename = filename.match(filenameRegex);
  if (matchedFilename) {
    const fileExtension = matchedFilename[0].slice(matchedFilename[0].lastIndexOf('.')).toLowerCase();
    return imageExtensions.includes(fileExtension);
  }
  return false;
}

/**
 * 判断文件类型
 */
export const getFileType = (fileName: string) => {
  // 后缀获取
  let suffix = '';
  // 获取类型结果
  let result: string | undefined = '';
  try {
    const flieArr = fileName.split('.');
    suffix = flieArr[flieArr.length - 1];
  } catch (err) {
    suffix = '';
  }
  // fileName无后缀返回 false
  if (!suffix) { return false; }
  suffix = suffix.toLocaleLowerCase();
  // 图片格式
  const imglist = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'ico', 'tiff', 'raw', 'heif', 'heic'];
  // 进行图片匹配
  result = imglist.find(item => item === suffix);
  if (result) {
    return 'image';
  }
  // 匹配txt
  const txtlist = ['txt'];
  result = txtlist.find(item => item === suffix);
  if (result) {
    return 'txt';
  }
  // 匹配 excel
  const excelist = ['xls', 'xlsx'];
  result = excelist.find(item => item === suffix);
  if (result) {
    return 'excel';
  }
  // 匹配 word
  const wordlist = ['doc', 'docx'];
  result = wordlist.find(item => item === suffix);
  if (result) {
    return 'word';
  }
  // 匹配 pdf
  const pdflist = ['pdf'];
  result = pdflist.find(item => item === suffix);
  if (result) {
    return 'pdf';
  }
  // 匹配 ppt
  const pptlist = ['ppt', 'pptx'];
  result = pptlist.find(item => item === suffix);
  if (result) {
    return 'ppt';
  }
  // 匹配 视频
  const videolist = ['mp4', 'm2v', 'mkv', 'rmvb', 'wmv', 'avi', 'flv', 'mov', 'm4v'];
  result = videolist.find(item => item === suffix);
  if (result) {
    return 'video';
  }
  // 匹配 音频
  const radiolist = ['mp3', 'wav', 'wmv'];
  result = radiolist.find(item => item === suffix);
  if (result) {
    return 'radio';
  }
  // 其他 文件类型
  return 'other';
}

/**
 * 文档预览
 */
export const previewFile = (url: string) => {
  const newTab = window.open();
  newTab!.location.href = url;
}

/**
 * 打开其他网站（新标签页）
 */
export const openSite = (url: string) => {
  const newTab = window.open();
  newTab!.location.href = url;
}